
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:hari_curly/src/common/event.dart';
import 'package:hari_curly/src/model/device_model.dart';
import 'package:loading_indicator/loading_indicator.dart';

import '../../../common/style.dart';
import '../../../common/utils.dart';
import '../../../components/layout.dart';
import '../../../states/device_connect_status.dart';

class DeviceScanPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _DeviceScanPageState();
}

class _DeviceScanPageState  extends State<DeviceScanPage>{

  late List<ScanResult> list = [];
  var subscription;
  @override
  void initState() {
    super.initState();
    _initScan();
  }
  Future<void>  _initScan() async {
    subscription=  FlutterBluePlus.onScanResults.listen((results) {
      if (results.isNotEmpty) {
        ScanResult r = results.last; // the most recently found device
        if(r.advertisementData.advName.startsWith("BZX80")&&!list.contains(r)){
          setState(() {
            list.add(r);
          });
        }

      }
    },
      onError: (e) => print(e),
    );

    await FlutterBluePlus.adapterState.where((val) => val == BluetoothAdapterState.on).first;
    await FlutterBluePlus.startScan(
        timeout: Duration(seconds:5));
  }

  @override
  void dispose() {
    FlutterBluePlus.stopScan();
    subscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

   return Scaffold(
       backgroundColor: pageBgColor,
       appBar: AppBarUnit(
         title: Text("device_scan_title".tr()),
         back: true,
         onPressed: () {
           context.pop();
         },
       ),
      body: Column(
        children: [
          Container(
              width: MediaQuery.of(context).size.width,
              height: 200,
              child: Padding(
                padding: EdgeInsets.symmetric(vertical: 0, horizontal: 4),
                child: Card(
                    color: unitBgColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 100,
                          height: 100,
                          child: LoadingIndicator(
                            indicatorType: Indicator.values[23],
                            strokeWidth: 1,
                            colors: [ Colors.white38],
                          ),
                        ),
                        SizedBox(height: 16),
                        Text('device_scan_tip'.tr()),
                      ]),
                )
              )
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            child:   Padding(
                padding: EdgeInsets.all(12),
                child: Text('device_scan_subTitle'.tr(),style: TextStyle(fontSize: 14,color: Colors.grey)),
              )
          ),
          Column(children: [
            ...list.map((item)=>
              Container(
                  width: MediaQuery.of(context).size.width,
                  constraints: BoxConstraints(minHeight: 40),
                  child: Padding(
                    padding: EdgeInsets.symmetric(vertical: 0, horizontal: 4),
                    child: Card(
                        color: unitBgColor,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        child: InkWell(
                          borderRadius: BorderRadius.circular(10.0),
                          child: Container(
                            padding: EdgeInsets.all(12),
                            child: Row(
                              children: [
                                Container(
                                  //圆角
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10.0),
                                    color: pageBgColor,
                                  ),
                                  alignment: Alignment.topLeft,
                                  padding: EdgeInsets.all(20),
                                  margin: EdgeInsets.fromLTRB(0, 0, 12, 0),
                                  child: Icon(
                                    Icons.bluetooth,
                                    color: Colors.white,
                                    size: 32,
                                  ),
                                ),
                                Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          item.advertisementData.advName.toUpperCase(),
                                          style: TextStyle(
                                              fontSize: 14, fontWeight: FontWeight.bold),
                                        ),
                                        Text(
                                          item.device.remoteId.toString(),
                                          style:
                                          TextStyle(fontSize: 12, color: Colors.grey),
                                        ),
                                      ],
                                    )),
                              ],
                            ),
                          ),
                          onTap: () {
                            DialogUtil.showLoadingDialog(context);
                            item.device.connect(timeout:  Duration(seconds: 5));
                            item.device.connectionState.listen((BluetoothConnectionState state) async {
                              if (state == BluetoothConnectionState.connected) {
                                FlutterBluePlus.stopScan();
                                subscription?.cancel();
                                Future.delayed(Duration(microseconds: 500), () async {
                                  DialogUtil.hideLoadingDialog();
                                  Fluttertoast.showToast(
                                      msg: "device_connect_ok".tr(),
                                      toastLength: Toast.LENGTH_SHORT,
                                      gravity: ToastGravity.CENTER,
                                      timeInSecForIosWeb: 1,
                                      backgroundColor: Colors.black45,
                                      textColor: Colors.white,
                                      fontSize: 16.0);
                                  DeviceModel device = DeviceModel(
                                    id: item.device.remoteId.toString(),
                                    name: item.advertisementData.advName,
                                    status: "1",
                                  );
                                 await DeviceModel.insert(device);
                                  await DeviceModel.connected(item.device.remoteId.toString());
                                  context.read<DeviceConnectStatus>().connect(device);
                                  context.push("/");
                                });
                              }else if (state == BluetoothConnectionState.disconnected&& context.read<DeviceConnectStatus>().state.status == "1") {
                                context.read<DeviceConnectStatus>().disconnect();
                                eventBus.fire(DeviceConnectStatusRefreshEvent());
                              }
                            });
                            Future.delayed(Duration(seconds: 5),(){
                              if(!item.device.isConnected){
                                DialogUtil.hideLoadingDialog();
                                Fluttertoast.showToast(
                                    msg: "device_connect_error".tr(),
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.CENTER,
                                    timeInSecForIosWeb: 1,
                                    backgroundColor: Colors.black45,
                                    textColor: Colors.white,
                                    fontSize: 16.0);
                              }

                            });
                          },
                        )),
                  ))
            ).toList(),

          ]),
        ]

      )
   );
  }
}

